package com.terry.activity.service.impl;

import com.terry.activity.bean.EnrollModel;
import com.terry.activity.bean.exception.DataAlreadyExistException;
import com.terry.activity.dao.IEnrollDao;
import com.terry.activity.service.IEnrollService;
import org.apache.commons.collections4.IteratorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Create On 18/4/22.
 *
 * @author TerrySolar
 */
@Service("EnrollService")
public class EnrollServiceImpl implements IEnrollService {

    @Resource
    private IEnrollDao enrollDao;

    @Override
    public boolean enroll(EnrollModel enroll) throws DataAlreadyExistException {

        if (enroll.getImgHash() == null || enroll.getImgHash().size() == 0 || enroll.getOpenId() == null) {
            return false;
        }
        EnrollModel oldEnroll = enrollDao.findEnrollModelByOpenId(enroll.getOpenId());

        // 如果之前有报名，则为修改
        if (oldEnroll != null) {
            throw new DataAlreadyExistException("请勿重复报名！");
        }

        // 将图片数组转为string储存
        StringBuilder imgHashBuffer = new StringBuilder();
        for (int i = 0;i < enroll.getImgHash().size(); i++) {
            imgHashBuffer.append(enroll.getImgHash().get(i));

            if (i != enroll.getImgHash().size() - 1) {
                imgHashBuffer.append(",");
            }
        }
        enroll.setImgHashJson(imgHashBuffer.toString());

        // 默认为未入围作品
        enroll.setEntry(false);

        enrollDao.save(enroll);

        return true;
    }

    @Override
    public EnrollModel retrieveEnroll(String openId) {
        if (openId == null || openId.equals("")) {
            return null;
        }

        return enrollDao.findEnrollModelByOpenId(openId);
    }

    @Override
    public List<EnrollModel> retrieveEnroll(Integer page, Integer size) {

        if (page == null && size == null) {
            return null;
        }

        Sort sort = Sort.by(Sort.DEFAULT_DIRECTION, "id");
        Pageable pageable = PageRequest.of(page, size, sort);

        Page<EnrollModel> pages = this.enrollDao.findAll(pageable);

        List<EnrollModel> enrolls = IteratorUtils.toList(pages.iterator());

        return enrolls;
    }
}
